package com.star.oauth2.client.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 消息管理控制器
 * 
 * @author star
 */
@Slf4j
@Controller
@RequestMapping("/messages")
public class MessagesController {

    /**
     * 消息管理页面
     * 
     * 处理从auth-success.html跳转而来的请求，获取URL参数中的token
     * 如果用户未通过验证（无token），前端JS会重定向到首页
     */
    @GetMapping
    public String messages(
            @RequestParam(required = false) String error,
            @RequestParam(required = false) String token,
            @RequestParam(required = false) String refresh_token,
            @RequestParam(required = false) String token_type,
            @RequestParam(required = false) String expires_in,
            Model model,
            RedirectAttributes redirectAttributes,
            HttpServletRequest request) {
            
        log.info("============= /messages 接口被访问 =============");
        log.info("请求URL: {}", request.getRequestURL().toString() + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
        log.info("请求方法: {}", request.getMethod());
        log.info("请求来源: {}", request.getRemoteAddr());
        log.info("token参数: {}", token != null ? (token.substring(0, Math.min(10, token.length())) + "...") : "null");
        
        // 检查是否有URL参数中的token（从auth-success.html跳转过来）
        if (token != null) {
            // 创建token响应对象
            Map<String, Object> tokenResponse = new java.util.HashMap<>();
            tokenResponse.put("access_token", token);
            tokenResponse.put("refresh_token", refresh_token);
            tokenResponse.put("token_type", token_type != null ? token_type : "Bearer");
            tokenResponse.put("expires_in", expires_in != null ? expires_in : "3600");
            
            // 将token响应传递给前端
            model.addAttribute("tokenResponse", tokenResponse);
            
            // 记录日志
            System.out.println("从URL参数获取到token: " + token.substring(0, Math.min(10, token.length())) + "...");
        } else {
            System.out.println("URL参数中没有token");
        }
        
        // 如果有错误信息，传递给前端
        if (error != null) {
            model.addAttribute("errorMessage", "访问消息管理系统时发生错误: " + error);
        }
        
        // 实际token验证由前端JavaScript完成
        // 如果没有token，前端JS会重定向到首页
        return "messages";
    }
}